package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser queryTodayBest(Long toUserId) {
//        从mongo的recommend_user表中查询，
//  命令：      db.getCollection('recommend_user').find({toUserId:1}).sort({score:-1}).limit(1)
        Query query = new Query(Criteria.where("toUserId").is(toUserId)); // 构建条件
        query.with(Sort.by(Sort.Direction.DESC,"score")); //安装缘分值降序
        query.limit(1); //取第一条数据
        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    @Override //查询推荐给指定用户的佳人
    public PageResult queryRecommendUserList(Long toUserId,Integer page, Integer pagesize) {
//        mongo命令 db.getCollection('recommend_user').find({toUserId:1}).limit(10).skip(0).sort({score:-1})
        Query query = new Query(Criteria.where("toUserId").is(toUserId));
        query.limit(pagesize).skip( ((page-1)* pagesize) +1 ); //这里的+1 会把今日佳人跳过
        query.with(Sort.by(Sort.Direction.DESC,"score"));
        List<RecommendUser> list = mongoTemplate.find(query, RecommendUser.class);
//        查询符合条件的总条数
        long count = mongoTemplate.count(query, RecommendUser.class);
        return new PageResult(page,pagesize,(int)count,list);
    }

    @Override
    public Long queryScore(Long userId, Long toUserId) {
        Query query = new Query(Criteria.where("toUserId").is(toUserId).and("userId").is(userId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if(recommendUser==null){
            return RandomUtils.nextLong(80,100);
        }
        return recommendUser.getScore().longValue();
    }
}
